package jp.bgbt.fles.app.bluetooth.util;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.bluetooth.le.BluetoothLeScanner;
import android.bluetooth.le.ScanCallback;
import android.content.Context;
import android.location.LocationManager;
import android.os.Build;
import android.os.Handler;


import com.common.utils.LogUtil;

import jp.bgbt.fles.app.MainApplication;


public class BleConnectUtil {

    private String TAG = getClass().getSimpleName();

    private static final int STOP_SCAN_TIME = 10 * 1000;

    private Runnable stopScanRunnable = new Runnable() {
        @Override
        public void run() {
            mBluetoothAdapter.stopLeScan(leScanCallback);
            LogUtil.d("停止扫描");

            listener.onScanStopped();
            listener.onScanStoppedWithTimeout();
        }
    };



    private BluetoothAdapter.LeScanCallback leScanCallback = new BluetoothAdapter.LeScanCallback() {
        @Override
        public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {
            if (listener != null)
                listener.onFindDevice(device);
        }
    };

    private BluetoothAdapter mBluetoothAdapter;
    private static Handler mHandler = new Handler();
    private OnBleConnectListener listener;

    public BleConnectUtil(OnBleConnectListener listener) {
        this.listener = listener;
    }

    public void prepareScan() {
        initBle();
        if (mBluetoothAdapter != null) {
            if (!mBluetoothAdapter.isEnabled()) {//蓝牙不可用，请求打开蓝牙
                if (listener != null)
                    listener.onBleDisabled();
            } else {
                continueScanBle();
            }
        }
    }

    public void destroy() {
        stopScan();
        listener = null;
    }


    private void initBle() {
        if (mBluetoothAdapter == null) {

            BluetoothManager manager = (BluetoothManager) MainApplication.getInstance()
                    .getSystemService(Context.BLUETOOTH_SERVICE);
            if (manager != null) {
                mBluetoothAdapter = manager.getAdapter();
            }
        }
    }

    public void continueScanBle() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            startScan();
            return;
        }
        if (isLocationEnable()) {
            startScan();
        } else {
            if (listener != null)
                listener.requestCoarseLocation();
        }
    }

    private void startScan() {
        if (mBluetoothAdapter != null) {
            mBluetoothAdapter.stopLeScan(leScanCallback);
            if (!mBluetoothAdapter.isEnabled())
                return;
            boolean canScan = mBluetoothAdapter.startLeScan(leScanCallback);
            mHandler.removeCallbacksAndMessages(null);
            mHandler.postDelayed(stopScanRunnable, STOP_SCAN_TIME);
            if (!canScan) { //不可进入扫描
                mBluetoothAdapter.disable();
                prepareScan();
            } else { //可进入扫描
                if (listener != null)
                    listener.onScanStarted();
                LogUtil.d("开始扫描蓝牙");
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    BluetoothLeScanner scanner = mBluetoothAdapter.getBluetoothLeScanner();
                    if (scanner != null)
                        scanner.startScan(new ScanCallback() {
                            @Override
                            public void onScanFailed(int errorCode) {
                                LogUtil.e("scanFailed " + errorCode);
                                if (errorCode == ScanCallback.SCAN_FAILED_APPLICATION_REGISTRATION_FAILED) {
                                    // Fails to start scan as app cannot be registered.
                                    mBluetoothAdapter.disable();
                                    if (listener != null)
                                        listener.onScanStoppedWithTimeout();
                                } else if (errorCode == 6) {
                                    // ScanCallback.SCAN_FAILED_SCANNING_TOO_FREQUENTLY  scan too frequently
                                    mBluetoothAdapter.disable();
                                    if (listener != null)
                                        listener.onScanStoppedWithTimeout();
                                }
                            }
                        });

                }
            }
        }
    }

    public static boolean isLocationEnable() {
        if(Build.VERSION.SDK_INT < Build.VERSION_CODES.M)
            return true;
        LocationManager locationManager
                = (LocationManager) MainApplication.getInstance().getSystemService(Context.LOCATION_SERVICE);
        boolean gps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        boolean network = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        if (gps || network) {
            return true;
        } else {
            return false;
        }
    }

    public void stopScan() {
        if (mBluetoothAdapter != null) {
            mHandler.removeCallbacksAndMessages(null);
            mBluetoothAdapter.stopLeScan(leScanCallback);
        }
        if (listener != null)
            listener.onScanStopped();
    }

    public void disableBle() {
        if (mBluetoothAdapter != null)
            mBluetoothAdapter.disable();
    }

    public interface OnBleConnectListener {

        void onFindDevice(BluetoothDevice device);

        void requestCoarseLocation();

        void onBleDisabled();

        void onScanStarted();

        void onScanStopped();

        void onScanStoppedWithTimeout();
    }

}
